package com.zy.fee.roadpark.activity.np;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.zy.fee.roadpark.R;
import com.zy.fee.roadpark.app.AppApplication;
import com.zy.fee.roadpark.config.Constants;
import com.zy.fee.roadpark.dao.CommonLogic;
import com.zy.fee.roadpark.dao.NpNodeRecordLogic;
import com.zy.fee.roadpark.model.M_NpNodeRecord;
import com.zy.fee.roadpark.view.CommonDialog;
import com.zygk.library.model.CommonResult;
import com.zygk.library.util.GlideImageLoader;
import com.zygk.library.util.HttpRequest;
import com.zygk.library.util.ImageUtil;
import com.zygk.library.util.ListUtils;
import com.zygk.library.util.ToastUtil;
import com.zygk.library.util.imagePicker.ImagePickerAdapter;
import com.zygk.library.util.imagePicker.NewImageGridActivity;
import com.zygk.library.view.LoadingDialog;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class LeaveNotPicActivity extends Activity
  implements ImagePickerAdapter.OnRecyclerViewItemClickListener {
  @BindView(R.id.recyclerView)
  RecyclerView recyclerView;
  @BindView(R.id.tv_plate_number)
  TextView tvPlateNumber;

  Context mContext;
  Activity mActivity;
  private LoadingDialog loadingDialog;

  public static final int IMAGE_ITEM_ADD = -1;
  public static final int REQUEST_CODE_SELECT = 100;
  public static final int REQUEST_CODE_PREVIEW = 101;
  private ImagePickerAdapter imagePickerAdapter;
  ArrayList<ImageItem> selectImageList; //当前选择的所有图片
  ArrayList<ImageItem> images = null;
  private int maxImgCount = 9;               //允许选择图片最大数
  private ImagePicker imagePicker;
  List<String> urlPaths = new ArrayList<>();
  int uploadIndex = 0;
  String pictures = "";
  M_NpNodeRecord npNodeRecord;
  private List<String> markpathList;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setFinishOnTouchOutside(true);
    setContentView(R.layout.activity_leave_not_pic);
    ButterKnife.bind(this);
    getWindow().setGravity(Gravity.CENTER);
    //设置布局填充满宽度
    WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
    layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
    layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
    getWindow().setAttributes(layoutParams);

    init();
  }

  private void init() {
    initData();
    initView();
  }

  private void initData() {
    mContext = this;
    mActivity = this;
    npNodeRecord = (M_NpNodeRecord) getIntent().getSerializableExtra("NodeRecord");
    selectImageList = new ArrayList<>();
    imagePickerAdapter = new ImagePickerAdapter(this, selectImageList, maxImgCount);
    imagePickerAdapter.setOnItemClickListener(this);
    initImagePicker();
    loadingDialog = new LoadingDialog(this);
    loadingDialog.setMessageText("加载中...");
  }

  private void initView() {
    tvPlateNumber.setText(npNodeRecord.getCarNumber());
    recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
    recyclerView.setHasFixedSize(true);
    recyclerView.setAdapter(imagePickerAdapter);
  }

  //请求拍照权限
  private void requestCameraPermission() {
    AndPermission.with(this)
      .requestCode(100)
      .permission(Manifest.permission.CAMERA)
      .callback(this)
      .start();
  }

  @PermissionYes(100)
  private void getPermissionYes(List<String> grantedPermissions) {
    takePic();
  }

  @PermissionNo(100)
  private void getPermissionNo(List<String> deniedPermissions) {
    ToastUtil.showMessage(mContext, "无摄像头权限, 请前往设置中心开启摄像头权限");
  }

  private void takePic() {
    //打开选择,本次允许选择的数量
    imagePicker.setSelectLimit(maxImgCount - selectImageList.size());
    Intent intent = new Intent(mActivity, NewImageGridActivity.class);
    intent.putExtra(NewImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
    startActivityForResult(intent, REQUEST_CODE_SELECT);
  }

  private void initImagePicker() {
    imagePicker = AppApplication.getImagePicker();
    imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
    imagePicker.setMultiMode(true);                      // 单选
    imagePicker.setShowCamera(false);                      //显示拍照按钮
    imagePicker.setCrop(false);                           //允许裁剪（单选才有效）
    imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
    imagePicker.setSelectLimit(maxImgCount);              //选中数量限制
    imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
    imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
    imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
    imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
    imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
  }

  @Override
  public void onItemClick(View view, int position) {
    switch (position) {
      case IMAGE_ITEM_ADD:
        if (AndPermission.hasPermission(mContext, Manifest.permission.CAMERA)) {
          takePic();
        } else {
          requestCameraPermission();
        }
        break;
      default:
        //打开预览
        Intent intentPreview = new Intent(mActivity, ImagePreviewDelActivity.class);
        intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS,
          (ArrayList<ImageItem>) imagePickerAdapter.getImages());
        intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
        intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
        startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
        break;
    }
  }

  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
      //添加图片返回
      if (data != null && requestCode == REQUEST_CODE_SELECT) {
        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
        if (images != null) {
          selectImageList.addAll(images);
          imagePickerAdapter.setImages(selectImageList);
        }
      }
    } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
      //预览图片返回
      if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
        if (images != null) {
          selectImageList.clear();
          selectImageList.addAll(images);
          imagePickerAdapter.setImages(selectImageList);
        }
      }
    }
  }

  private void uploadPic(int index) {
    String fileName = UUID.randomUUID().toString() + markpathList.get(index).substring(
      markpathList.get(index).lastIndexOf("."));

    CommonLogic.do_upload_pic(mContext, true, markpathList.get(index), fileName,
      new HttpRequest.HttpCallback() {
        @Override
        public void onStart() {
        }

        @Override
        public void onSucceed(Object obj) {
          CommonResult result = (CommonResult) obj;
          //重新设置用户信息
          urlPaths.add(result.getData());
          if (uploadIndex < markpathList.size() - 1) {
            uploadIndex++;
            uploadPic(uploadIndex);
          } else {
            pictures = ListUtils.join(urlPaths, ",");
            applyHandle(npNodeRecord.getNodeRecordID(), 0, pictures);
          }
        }

        @Override
        public void onFailed() {
          dismissPd();
        }

        @Override
        public void onFinish() {
        }
      });
  }

  private void applyHandle(String nodeRecordID, int state, String pic) {
    NpNodeRecordLogic.npnode_record_apply_handle(mContext, nodeRecordID, state, pic,
      new HttpRequest.HttpCallback() {
        @Override
        public void onStart() {
        }

        @Override
        public void onSucceed(Object obj) {
          ToastUtil.showMessage(mContext, "处理成功");
          sendBroadcast(new Intent(Constants.BROADCAST_REFRESH_NODE_RECORD_LIST));
          finish();
        }

        @Override
        public void onFailed() {
          dismissPd();
        }

        @Override
        public void onFinish() {
          dismissPd();
        }
      });
  }

  public void showPd() {
    try {
      if (loadingDialog != null && !loadingDialog.isShowing()) {
        loadingDialog.show();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  protected void showNoCancelPd() {
    try {
      if (loadingDialog != null && !loadingDialog.isShowing()) {
        loadingDialog.setCanceledOnTouchOutside(false);
        loadingDialog.setCancelable(false);
        loadingDialog.show();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void dismissPd() {
    try {
      if (loadingDialog != null && loadingDialog.isShowing()) {
        loadingDialog.dismiss();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  @OnClick({
    R.id.tv_no, R.id.tv_yes
  })
  public void onViewClicked(View view) {
    Intent intent;
    switch (view.getId()) {
      case R.id.tv_no:
        finish();
        break;
      case R.id.tv_yes:
        if (!ListUtils.isEmpty(selectImageList)) {
          showNoCancelPd();
          new Thread(new Runnable() {
            @Override
            public void run() {
              List<String> pathList = new ArrayList<>();
              for (ImageItem item : selectImageList) {
                pathList.add(item.path);
              }
              markpathList = ImageUtil.addWatermark(pathList);
              uploadPic(0);
            }
          }).start();
        } else {
          ToastUtil.showMessage(mContext, "至少上传一张图片");
        }
        break;
    }
  }
}
